package com.hzw.saas.web.admin.job.task;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzw.saas.api.hpc.IHpcAccountProviderService;
import com.hzw.saas.api.hpc.bo.HpcAccountProviderBo;
import com.hzw.saas.api.hpc.enums.HpcProviderType;
import com.hzw.saas.common.config.util.RedisUtil;
import com.hzw.saas.common.quartz.model.ScheduleJob;
import com.hzw.saas.common.util.constants.CacheConsts;
import com.hzw.saas.service.hpc.service.IQingCloudService;
import com.hzw.saas.service.hpc.service.bo.ClusterUsageBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("hpcClusterUsageTask")
public class HpcClusterUsageTask {

    @Resource
    private IHpcAccountProviderService providerService;
    @Resource
    private IQingCloudService qingCloudService;
    @Resource
    private ObjectMapper objectMapper;


    public void execute(ScheduleJob scheduleJob) throws Exception {
        String params = scheduleJob.getParams();
        JsonNode jsonNode = objectMapper.readTree(params);
        long cacheTime = jsonNode.get("cacheTime").asLong(60 * 60);

        // 循环中异常 仍需继续循环
        List<Exception> exceptions = new ArrayList<>();
        providerService.list(new HpcAccountProviderBo().setProviderCode(HpcProviderType.QY.value()))
                .forEach(providerBo -> {
                    try {
                        ClusterUsageBO clusterUsage = qingCloudService.getClusterUsage(providerBo);
                        RedisUtil.set(CacheConsts.KEY_CLUSTER_USAGE + providerBo.getProviderId(), clusterUsage, cacheTime);
                    } catch (Exception ex) {
                        exceptions.add(ex);
                    }
                });
        if (!CollectionUtils.isEmpty(exceptions)) {
            String msg = exceptions.stream().map(Exception::getMessage).collect(Collectors.joining(","));
            throw new Exception(msg);
        }
    }
}
